<?php

/**
 * @classname 项目公共类
 * @classaccess private
 * @decription 项目程序的公共类
 * @author 张旭刚
 * @updateTime 2020年05月12日
 */

namespace employee\controllers;

use Yii;
use employee\models\Users;
use employee\models\UserTokens;

class PublicController extends \common\controllers\CommonController {

    public $enableCsrfValidation;
    protected $debug;
    protected $user;
    protected $userId;
    protected $isLogin;
    protected $token;

    public function __construct($id, $module, $config = array()) {
        parent::__construct($id, $module, $config);
        $this->enableCsrfValidation = false;
        $this->getDebug();
        $this->getHeaders();
        $this->checkLogin();
    }
    
    /**
     * 获得图片地址
     * @param type $pic
     * @return type
     */
    protected function getFace($pic) {
        if (empty($pic)) {
            return Yii::$app->params['pic'] . 'nocover.jpg';
        } else {
            $fileName = basename($pic);
            $picRealPath = $this->setting('pic_realpath_path');
            $realPath = $picRealPath . $fileName;
            return !file_exists($realPath) ? Yii::$app->params['pic'] . 'nocover.jpg' : Yii::$app->params['pic'] . $fileName;
        }
    }
    
    /**
     * 设置Headers
     */
    private function getHeaders(){
        $this->headers = Yii::$app->request->headers;
        $url = $this->getUrl();
        if($url !== '/site/guid' && $url !== '/' && (!isset($this->headers['guid']) || empty($this->headers['guid']))){
            return $this->renderJson(['code' => 0, 'msg' => 'GUID不存在', 'result' => false, 'errorCode' => 201001]);
        }
        $this->guid = $this->headers['guid'];
        
    }
    
    /**
     * 检查是否登录了
     */
    private function checkLogin(){
        //判断是否需要登录
        $this->isLogin = false;
        $notLogins = $this->getAppNotLogins();
        $action = $this->getAction();
        $this->token = isset($this->headers['userToken']) ? $this->headers['userToken'] : '';

        if(!in_array($action, $notLogins)){
            if(empty($this->token)){
                return $this->renderJson(['code' => 0, 'msg' => '登录失败或超时', 'result' => false, 'errorCode' => 201004]);
            }
            $tokens = $this->getTokens();
            $this->currentUser($tokens['userid']);
        }
    }
    
    private function currentUser($userId){
        $user = Users::find()->where(['id' => $userId])->asArray()->one();
        if(empty($user)){
            return $this->renderJson(['code' => 0, 'msg' => '登录失败或超时', 'result' => false, 'errorCode' => 201003]);
        }
        $this->user = $user;
        $this->userId = $user['id'];
        $this->isLogin = true;
    }


    /**
     * Tokens
     */
    private function getTokens(){
        $tokens = Usertokens::find()->where(['token' => $this->headers['userToken']])->asArray()->one();
        $long = time() - $tokens['ctime'];
        $tokenLong = intval($this->setting('employee_login_token_limit_long'));
        if($long > $tokenLong){
            return $this->renderJson(['code' => 0, 'msg' => '登录失败或超时', 'result' => false, 'errorCode' => 201002]);
        }
        return $tokens;
    }

    /**
     * 获得不需要登录的Action
     */
    private function getAppNotLogins(){
        $str = $this->setting('api_employee_not_login_actions');
        $notLogins = explode(',', $str);
        return $notLogins;
    }

    /**
     * 获取当前Action
     * @return type
     */
    private function getAction(){
        $action = Yii::$app->request->url;
        if($action == '/'){return 'site/index';}
        $str = substr($action, 1, strlen($action));
        $strs = explode('?', $str);
        $s = explode('&', $strs[0]);
        return $s[0];
    }
    
    /**
     * 设置debug状态
     */
    private function getDebug(){
        $debug = $this->setting('api_debug');
        $this->debug = empty($debug) ? $this->debug = 'no' : $debug;
    }
}
